const RtcTokenBuilder = require('./token/RtcTokenBuilder').RtcTokenBuilder;
const RtcRole = require('./token/RtcTokenBuilder').Role;
const AgoraAPIQueue = require('../AgoraAPIQueue');
const AgoraAPIBase = require('../AgoraAPIBase');
const errors = require('../error');
const logger = require('../../utils').getLogger(__filename);
const _ = require('lodash');
const queue = new AgoraAPIQueue({ logger });
const config = require('config');

module.exports = class APIStart extends AgoraAPIBase {
	constructor(data, modal) {
		super(data, modal);
		this.logger = logger
	}

	getToken(channelName) {
		return RtcTokenBuilder.buildTokenWithUid(this.appId, this.appCertificate, channelName, 0, RtcRole.PUBLISHER, Math.floor(Date.now() / 1000) + 24 * 60 * 60);
	}

	async run() {
		return queue.push(this.createArgs()).then(j => {
			if (j.resourceId && j.sid) {
				return j
			}
			return Promise.reject(new errors.ResultFormat({ data: this.data, response: j }));
		});
	}


	createArgs() {
		let { channelName, uid, rid, resourceId, type, prefix, clientRequest } = this.data;
		let path = `/v1/apps/${this.appId}/cloud_recording/resourceid/${resourceId}/mode/${this.modal}/start`;
		let body = {
			cname: channelName,
			uid: rid.toString(),
			clientRequest: {
				token: this.getToken(channelName),
				storageConfig: config.get('aliyun.storageConfig')
			}
		};
		body = _.defaultsDeep(body, { clientRequest })
		if (this.modal === 'mix') {
			body.clientRequest.recordingConfig = {
				transcodingConfig: {
					width: 640,
					height: 480,
					fps: 15,
					bitrate: 500,
					backgroundColor: '#ffffff',
					mixedVideoLayout: 1,
				},
				maxIdleTime: 300
			};
			body.clientRequest.recordingFileConfig = {
				avFileType: ['hls', 'mp4']
			};
		} else {
			body.clientRequest.recordingConfig = {
				subscribeUidGroup: 1
			};
			if (type === 'audio') {
				body.clientRequest.recordingConfig['subscribeAudioUids'] = [uid.toString()];
			} else {
				body.clientRequest.recordingConfig['subscribeVideoUids'] = [uid.toString()];
			}
		}
		let options = {
			body: JSON.stringify(body)
		};
		return { url: path, options, type: 'post' };
	}

};
